<template>
	<view class="container">
		<u-navbar back-icon-color="#000" :back-text-style="{ color: '#000' }" title-color="#000" back-text="返回" title="编辑账号信息" :is-fixed="true" :border-bottom="false" :background="navBarBackground">
			<!-- #ifndef MP-WEIXIN -->
			<!-- <view class="navbar-save" slot="right" @tap.stop="saveForm">保存</view> -->
			<!-- #endif -->
		</u-navbar>
		<template v-if="isLoad">
			<u-form class="form" :label-style="labelStyle" :model="base" ref="uForm">
				<u-form-item label-width="300rpx" label="头像">
					<view class="form-right"><image @tap="chooseFaceImage" class="user-face" :src="base.avatar ? base.avatar.file_path : userInfo.avatar.file_path" mode="aspectFill"></image></view>
				</u-form-item>
				<u-form-item label-width="300rpx" label="昵称">
					<view class="form-right"><u-input input-align="right" maxlength="20" :clearable="false" :style="inputStyle" class="base-input" v-model="base.nickName" /></view>
				</u-form-item>
				<u-form-item label-width="300rpx" label="性别">
					<view class="form-right"><u-input input-align="right" @click="showSexToast" :disabled="true" :style="inputStyle" class="base-input" v-model="base.gender" /></view>
				</u-form-item>
				<u-form-item label-width="300rpx" label="出生日期">
					<view class="form-right"><u-input input-align="right" @click="calendarShow = true" :disabled="true" :style="inputStyle" class="base-input" v-model="base.birthday" /></view>
				</u-form-item>

				<u-form-item label-width="300rpx" label="所在地区">
					<view :disabled="true" class="form-right"><u-input input-align="right" @click="regionShow = true" :disabled="true" :style="inputStyle" class="base-input" v-model=" base.province + ' ' + base.city + ' ' + base.district" /></view>
				</u-form-item>
				<u-form-item label-width="300rpx" label="邮箱">
					<view class="form-right"><u-input input-align="right" :style="inputStyle" placeholder="请输入常用邮箱" class="base-input" v-model="base.email" /></view>
				</u-form-item>
				<u-form-item label-position="top" label-width="300rpx" :label="`兴趣爱好(${labelList.length}/${labelMax})`">
					<view class="form-bottom">
						<view class="label-group">
							<view class="label-item" @tap.stop="selecteHobby" :data-index="index" :class="{ activity: label.selected }" v-for="(label, index) in labelArray" :key="label.id">{{ label.name }}</view>
						</view>
					</view>
				</u-form-item>
			</u-form>
			<view class="submit-space"></view>
			<view class="submit-area"><u-button @click="saveForm" type="main-theme">保存</u-button></view>
			<u-select v-model="regionShow" mode="mutil-column-auto" :list="regionList" @confirm="confirmRegionPicker"></u-select>
			<u-picker mode="selector" :default-selector="selectorDefault" :range="selectorRange" :title="paramTitle" v-model="selectorShow" range-key="name" @confirm="confirmSelector"></u-picker>
			<u-picker mode="multiSelector" :default-selector="twoSelectDefault" :range="[twoSelectRangeFirst, twoSelectRangeSecond]" :title="paramTitle" v-model="twoSelectShow" range-key="name" @confirm="confirmTwoSelector" @columnchange="changeTwoSelect"></u-picker>
			<param-search-manager v-if="itemIndex != null" :defaultValue="params[itemIndex].setting" @cancel="cancelParamSearch" @confirm="confirmParamSearch" v-model="searchPopupShow" :height="searchPopupHeight" :keyname="params[itemIndex].alias" :title="paramTitle"></param-search-manager>
		</template>
	</view>
</template>

<script>
import moment from '@/utils/Moment.js';
import UserDataMixins from '@/mixins/user-data-mixins.js';
import paramSearchManager from '../components/custom/param-search-manager.vue';
export default {
	components: { paramSearchManager },
	mixins: [UserDataMixins],
	data() {
		return {
			base: {},
			calendarShow: false,
			regionShow: false,
			labels: [],
			labelMax: 10,
			labelList: [],
			avatar_id: '',
			maxDate: '',
			minDate: '',
			maxYear: '',
			minYear: '',
			regionList: []
		};
	},
	onLoad() {
		const maxDate = moment().subtract(18, 'years');
		this.maxDate = maxDate.format('YYYY-MM-DD');
		this.maxYear = maxDate.year();
		const minDate = moment().subtract(100, 'years');
		this.minDate = minDate.format('YYYY-MM-DD');
		this.minYear = minDate.year();
		this.$u.api.getRegionList().then(res => {
			// const regionList = res.data.data;
			// for (let i = 0; i < regionList.length; i++) {
			// 	for (let j = 0; j < regionList[i].children.length; j++) {
			// 		delete regionList[i].children[j].children;
			// 	}
			// }
			this.regionList = res.data.data;
		});
		this.getData();
		uni.$on('croperComplete', this.croperComplete);
	},

	onShow() {},
	onUnload() {
		uni.$off('croperComplete', this.croperComplete);
	},
	computed: {
		labelIds: function() {
			const labelIds = [];
			for (let i = 0; i < this.labelList.length; i++) {
				labelIds.push(this.labelList[i].id);
			}
			return labelIds;
		},

		labelArray: function() {
			const labelArray = [];
			for (let i = 0; i < this.labels.length; i++) {
				const label = this.labels[i];
				label.selected = this.labelIds.indexOf(label.id) >= 0;
				labelArray.push(label);
			}
			return labelArray;
		}
	},
	methods: {
		getData() {
			this.$u.api.getUserBasic().then(res => {
				this.base = res.data.user;
				this.labels = res.data.labels;
				if (this.base.label) {
					this.labelList = JSON.parse(this.base.label);
				} else {
					this.labelList = [];
				}
				this.isLoad = true;
			});
		},
		selecteHobby(e) {
			const index = e.currentTarget.dataset.index;
			const pos = this.labelIds.indexOf(this.labels[index].id);

			if (pos >= 0) {
				this.labelList.splice(pos, 1);
			} else {
				if (this.labelList.length < this.labelMax) {
					this.labelList.push(this.labels[index]);
				}
			}
		},
		confirmBirthdayPicker(e) {
			const { year, month, day } = e;
			this.$set(this.base, 'birthday', [year, month, day].join('-'));
		},
		confirmRegionPicker(e) {
			this.$set(this.base, 'province', e[0].label);
			this.$set(this.base, 'city', e[1].label);
			this.$set(this.base, 'district', e[2].label);
		},
		showSexToast() {
			this.$u.toast('实名认证后自动选择，无需修改');
		},
		croperComplete(data) {
			if (data.fromToken === this.viewToken) {
				const dataRes = data.res;
				const oldAvatar = this.base.avatar.file_path;
				this.$set(this.base.avatar, 'file_path', dataRes.path);
				uni.showLoading({
					mask: true,
					title: '上传中...'
				});
				this.$u.api
					.uploadImage(dataRes.source, { param: JSON.stringify(dataRes.param) })
					.then(res => {
						this.avatar_id = res.data.file_id;
						this.$set(this.base.avatar, 'file_path', res.data.file_path);
						uni.hideLoading();
					})
					.catch(e => {
						uni.hideLoading();
						this.$set(this.base.avatar, 'file_path', oldAvatar);
						this.$u.toast('上传失败');
					});
			}
		},
		chooseFaceImage() {
			uni.chooseImage({
				count: 1,
				success: res => {
					this.navigateTo({
						url:
							'/pageSupport/supplement/cropper' +
							this.$u.queryParams({
								imagePath: res.tempFilePaths[0],
								viewToken: this.viewToken,
								aspectRatio: 1,
								initialBoxWidthRatio: 1,
								minBoxWidthRatio: 0.5
							})
					});
				}
			});
		},
		saveForm() {
			const form = {};
			form.nickName = this.base.nickName;
			if (this.avatar_id) {
				form.avatar_id = this.avatar_id;
			}
			form.birthday = this.base.birthday;
			form.country = this.base.country || '中国';
			form.province = this.base.province;
			form.city = this.base.city;
			form.district = this.base.district;
			form.email = this.base.email || '';
			form.label = JSON.stringify(this.labelList);
			this.$u.api.saveUserBasic(form).then(res => {
				this.$u.toast('账号信息保存成功');
				this.navigateBack();
			});
		}
	}
};
</script>

<style lang="scss">
.container {
}
.form {
	background-color: #fff;
}
.base-input {
	text-align: right;
}
.form-right {
	width: 100%;
	padding-right: 30rpx;
	display: flex;
	align-items: center;
	justify-content: flex-end;
}
.user-face {
	height: 100rpx;
	width: 100rpx;
	border-radius: 6rpx;
}
.form-bottom {
	padding: 0 30rpx;
}
.label-group {
	display: flex;
	flex-wrap: wrap;
	.label-item {
		height: 50rpx;
		margin-right: 20rpx;
		border-radius: 30rpx;
		border: 2rpx solid #ddd;
		display: flex;
		align-items: center;
		padding: 0 25rpx;
		color: #3d3d3d;
		margin-bottom: 15rpx;
		font-size: 26rpx;
		&.activity {
			background-color: $theme-main-color;
			color: #fff;
			border-color: $theme-main-color;
		}
	}
}
.submit-space,
.submit-area {
	height: 120rpx;
}
.submit-area {
	padding: 20rpx 32rpx;
	position: fixed;
	width: 750rpx;
	bottom: 0;
	z-index: 20;
	background-color: #fff;
}
.navbar-save {
	margin-right: 10px;
}
</style>
